<template>
  <view class="content">
    <view class="top">

    </view>
    <view class="ts-column ts-center" style="margin-top: -150upx;">
      <view class="ts-row">
        <image class="logo" src="../../static/images/logo.png" mode=""></image>
      </view>
      <view class="ts-row">
        产教融合
      </view>
    </view>



    <view class="ts-flex ts-column ts-center">
      <!-- #ifdef APP-PLUS -->
      <view @tap="openLink()" @longtap="save">
        <qrcode :val="qrcodeLink" :size="qrsize" ref="qrcode"></qrcode>
      </view>
      <!-- #endif -->
      
      <!-- #ifndef APP-PLUS -->
      <view @tap="openLink()">
        <qrcode :val="qrcodeLink" :size="qrsize" ref="qrcode"></qrcode>
      </view>
      <!-- #endif -->
      
      <view><text>{{qrcodeLink}}</text></view>
      <view><text>邀请码：UVWROO</text></view>
    </view>

    <view class="ts-row ts-padding ts-flex-item">
      <!-- #ifdef APP-PLUS -->
      <ts-button class="ts-row ts-flex-item" @click="save" type="primary">保存二维码</ts-button>
      <!-- #endif -->
      <!-- #ifndef H5 -->
      <ts-button class="ts-row ts-flex-item" @click="sharurl" type="error">复制推广链接</ts-button>
      <!-- #endif -->
    </view>

    <!-- #ifdef APP-PLUS -->
    <view class="ts-row ts-padding ts-center" v-if="providerList.length > 0">
      <block v-for="(value,index) in providerList" :key="index">
        <view class="ts-row">
          <!-- <button type="primary" v-if="value" :disabled="shareType === 5 && value.name !== '分享到微信好友'" @tap="share(value)">{{value.name}}</button> -->
          <view class="ts-padding">
            <image v-if="value" class="icon" :src="'../../static/app-plus/providers/'+value.id+'.png'" @tap="share(value)" />
            </image>
          </view>
        </view>
      </block>
    </view>
    <!-- #endif -->
    <!-- #ifdef MP -->
    <view  class="ts-row ts-flex-item">
      <button type="primary" size="default" open-type="share">分享</button>
    </view>
    <!-- #endif -->

    <view class="ts-column" style="padding-left: 100upx; line-height: 1.8em;">
      <text>1、好友识别二维码通过手机号进行注册</text>
      <text>2、也可分享此页面到微信或QQ邀请好友注册</text>
      <text>3、注册完成后您即可得到相应的积分</text>
    </view>

  </view>
</template>

<script>
  import qrcode from '../../components/qrcode/qrcode.vue'

  import {
    mapState,
    mapMutations,
    mapActions
  } from 'vuex'

  export default {
    components: {
      qrcode
    },
    data() {
      return {
        providerList: [],
        // type: 0,

        shareType: 0,
        shareImage: 'https://img-cdn-qiniu.dcloud.net.cn/uniapp/app/share-logo@3.png',
        // sourceLink: 'https://uniapp.dcloud.io',
        shareTitle: '欢迎体验优职道',
        shareText: '专注在校学生的实习、就业，破解企业招工难题，提供精准就业、精准招聘服务！',
        shareLink: 'http://www.zengqs.com', //生成的二维码的链接，点解分享链接到改页面
        qrcodeLink: 'http://www.zengqs.com/share?id=3228969',
        qrsize: 150,
        inviterCode: 'UVWROO'
      }
    },
    computed: {
      ...mapState(['hasLogin']),
    },

    onLoad() {


      //必须延时，否则报错
      setTimeout(() => {
        this.qrsize = uni.upx2px(300);
        this.$refs.qrcode.creatQrcode();

        console.log(this.$refs.qrcode.img);

      }, 1000)

      //#ifdef APP-PLUS
      uni.getProvider({
        service: 'share',
        success: (e) => {
          // console.log('success', e);
          let data = []
          for (let i = 0; i < e.provider.length; i++) {
            switch (e.provider[i]) {
              case 'weixin':
                data.push({
                  name: '分享到微信好友',
                  id: 'weixin',
                  sort: 0
                })
                data.push({
                  name: '分享到微信朋友圈',
                  id: 'weixin',
                  type: 'WXSenceTimeline',
                  sort: 1
                })
                break;

              case 'qq':
                data.push({
                  name: '分享到QQ',
                  id: 'qq',
                  sort: 2
                })
                break;
              case 'sinaweibo':
                data.push({
                  name: '分享到新浪微博',
                  id: 'sinaweibo',
                  sort: 3
                })
                break;
              default:
                break;
            }
          }
          this.providerList = data.sort((x, y) => {
            return x.sort - y.sort
          });
        },
        fail: (e) => {
          console.log('获取登录通道失败', e);
          uni.showModal({
            content: '获取登录通道失败',
            showCancel: false
          })
        }
      });
      //#endif
    },
    onShareAppMessage() {
      return {
        title: this.shareText ? this.shareText : "欢迎",
        path: '/pages/tabBar/component/component',
        imageUrl: this.shareImage
      }
    },

    methods: {
      // ...mapMutations(['logout']),
      // ...mapActions(['getUserInfo', 'logout']),
      ...mapActions({
        getUserInfo: 'user/getUserInfo',
        // logout: 'logout'
      }),
      //复制分享链接
      sharurl() {
        //#ifndef H5
        uni.setClipboardData({
          data: this.shareLink,
          success: function() {
            console.log('success');
            uni.showModal({
              title: '复制成功',
              content: '内容已复制到粘贴板，可前往其他应用粘贴查看。',
              showCancel: false,
              success: function(res) {
                if (res.confirm) {
                  //console.log('用户点击确定');
                } else if (res.cancel) {
                  //console.log('用户点击取消');
                }
              }
            });
          }
        });
        //#endif
      },
      //保存图片到相册  
      //#ifdef APP-PLUS
      save() {

        uni.showActionSheet({
          itemList: ['保存图片到相册'],
          success: () => {
            plus.gallery.save('https://img.cdn.aliyun.dcloud.net.cn/guide/uniapp/app_download.png', function() {
              uni.showToast({
                title: '保存成功',
                icon: 'none'
              });
            }, function() {
              uni.showToast({
                title: '保存失败，请重试！',
                icon: 'none'
              });
            });
          }
        });

      },
      //#endif

      openLink() {
        //#ifdef APP-PLUS
        plus.runtime.openWeb(this.shareLink)
        //#endif   

        // #ifdef H5
        window.location.href = this.shareLink;
        // #endif
      },

      async share(e) {
        console.log('分享通道:' + e.id + '； 分享类型:' + this.shareType);




        if (!this.shareText && (this.shareType === 1 || this.shareType === 0)) {
          uni.showModal({
            content: '分享内容不能为空',
            showCancel: false
          })
          return;
        }

        if (!this.shareImage && (this.shareType === 2 || this.shareType === 0)) {
          uni.showModal({
            content: '分享图片不能为空',
            showCancel: false
          })
          return;
        }

        if (e.id === 'qq') {
          this.shareType = 1; //QQ不支持图文分享
        }

        let shareOPtions = {
          provider: e.id,
          scene: e.type && e.type === 'WXSenceTimeline' ? 'WXSenceTimeline' : 'WXSceneSession', //WXSceneSession”分享到聊天界面，“WXSenceTimeline”分享到朋友圈，“WXSceneFavorite”分享到微信收藏     
          type: this.shareType,
          success: (e) => {
            console.log('success', e);
            uni.showModal({
              content: '分享成功',
              showCancel: false
            })
          },
          fail: (e) => {
            console.log('fail', e)
            uni.showModal({
              content: e.errMsg,
              showCancel: false
            })
          },
          complete: function() {
            console.log('分享操作结束!')
          }
        }

        switch (this.shareType) {
          case 0: //图文
            shareOPtions.summary = this.shareText;
            shareOPtions.imageUrl = this.shareImage;
            shareOPtions.title = this.shareTitle;
            shareOPtions.href = this.shareLink;
            break;
          case 1: //纯文字
            shareOPtions.summary = this.shareText;
            break;
          case 2: //纯图片
            shareOPtions.imageUrl = this.shareImage;
            break;
          case 5: //小程序
            shareOPtions.imageUrl = this.shareImage;
            shareOPtions.title = this.shareTitle;
            shareOPtions.miniProgram = {
              id: 'gh_33446d7f7a26',
              path: '/pages/tabBar/component/component',
              webUrl: this.shareLink,
              type: 0
            };
            break;
          default:
            break;
        }

        if (shareOPtions.type === 0 && plus.os.name === 'iOS') { //如果是图文分享，且是ios平台，则压缩图片 
          shareOPtions.imageUrl = await this.compress();
        }
        if (shareOPtions.type === 1 && shareOPtions.provider === 'qq') { //如果是分享文字到qq，则必须加上href和title
          shareOPtions.href = this.shareLink;
          shareOPtions.title = this.shareTitle;
        }


        uni.share(shareOPtions);
      },

      chooseImage() {
        uni.chooseImage({
          count: 1,
          sourceType: ['album', 'camera'],
          sizeType: ['compressed', 'original'],
          success: (res) => {
            this.shareImage = res.tempFilePaths[0];
          }
        })
      },
      compress() { //压缩图片 图文分享要求分享图片大小不能超过20Kb
        console.log('开始压缩');
        let img = this.shareImage;
        return new Promise((res) => {
          var localPath = plus.io.convertAbsoluteFileSystem(img.replace('file://', ''));
          console.log('after' + localPath);
          // 压缩size
          plus.io.resolveLocalFileSystemURL(localPath, (entry) => {
            entry.file((file) => { // 可通过entry对象操作图片 
              console.log('getFile:' + JSON.stringify(file));
              if (file.size > 20480) { // 压缩后size 大于20Kb
                plus.zip.compressImage({
                  src: img,
                  dst: img.replace('.jpg', '2222.jpg').replace('.JPG', '2222.JPG'),
                  width: '10%',
                  height: '10%',
                  quality: 1,
                  overwrite: true
                }, (event) => {
                  console.log('success zip****' + event.size);
                  let newImg = img.replace('.jpg', '2222.jpg').replace('.JPG', '2222.JPG');
                  res(newImg);
                }, function(error) {
                  uni.showModal({
                    content: '分享图片太大,需要请重新选择图片!',
                    showCancel: false
                  })
                });
              }
            });
          }, (e) => {
            console.log('Resolve file URL failed: ' + e.message);
            uni.showModal({
              content: '分享图片太大,需要请重新选择图片!',
              showCancel: false
            })
          });
        })
      },
    }
  }
</script>

<style>
  page {
    min-height: 100%;

  }

  view {
    line-height: 1.8em;
  }

  /*  view {
    border: #000000 solid 1px;
    padding: 10px;
  } */

  .content {
    display: flex;
    flex-direction: column;
    flex: 1;
  }


  .top {
    width: 100%;
    height: 300upx;
    background: url(http://pds.jyt123.com/wxtest/banner.png) no-repeat;
    background-size: 100%;
    background-position: center center;
  }

  .logo {
    width: 200upx;
    height: 200upx;
  }

  .qrcode {
    width: 300upx;
    height: 300upx;
  }

  .icon {
    width: 80upx;
    height: 80upx;
  }
</style>
